const api = require('../config/api')
const { createHash, createToken, verifyToken } = require('../common')

function permission(noAuth) {
    return async function (ctx, next) {
        try {
            let token = (ctx.request.headers)['authorization'];
            if (!token) {       // 没带token
                return ctx.body = { status: 'fail', data: 'token no found' };
            } else {            // 带了token
                let result = verifyToken(token);
                if (result == false) {      // 无效的token
                    return ctx.body = { status: 'fail', data: '无效的token'  };
                } else {        // token有效
                    if (noAuth.indexOf(result.identify) != -1) {      // 权限在不能继续访问
                        return ctx.body = { status: 'fail', data: '权限不够' };
                    } else {        // 权限可以访问
                        let newToken = createToken({ _id: result._id, name: result.name, identify: result.identify });
                        ctx.set('Authorization', newToken);
                        return next();
                    }
                }
            }
        } catch (e) {
            return ctx.body = { status: 'fail', data: e.message, }
        }
    }
}


module.exports = async function (app, router) {
    try {
        api.forEach((item, index, array) => {
            let arr = item.url.split('/');
            let controller = require('../controllers/' + arr[1]);
            if (item.noAuth.length == 0 && item.needLogin == false) {
                router[item.method](item.url, controller[arr[2]]);
            } else {
                router[item.method](item.url, permission(item.noAuth), controller[arr[2]]);
            }
        })
        return app.use(router.routes())
    } catch (e) {
        return console.log(e)
    }
}